<template>
  <div class="lotteryHead">
    <div class="lotteryHeadMain">
      <div class="lotteryHeadLeft displayFlex">
        <div class="lotteryHeadLogo">
          <img :src="lotteryHeaderData.icon" alt="">
        </div>
        <div class="lotteryHeadText">
          <h1>{{lotteryHeaderData.name}}</h1>
          <section>
            <p>第 <span>{{lotteryHeaderData.nowNumber}}</span> 期</p>
            <p>总共: <span>{{lotteryHeaderData.periods}}</span>期</p>
          </section>
          <div class="lotteryPlayTab">
            <span v-for="(lot,i) in lotteryPlayTabData" :class="{'active': parseInt(tabPlayTrue) === i}"
                  @click="creditTab(i)">{{lot}}</span>
          </div>
        </div>
      </div>
      <div class="lotteryHeadCont">
        <div class="lotContMain" v-if="!isStopSale">
          <div class="lotContTitle" v-if="!stopBet">已开盘，距离投注截止还有：</div>
          <div class="lotContTitle" v-if="stopBet">封盘时间：</div>
          <div class="lotContTime">
            <span class="bgNum">
              <span>{{countDownStr.charAt(0)}}</span>
              <span>{{countDownStr.charAt(1)}}</span>
            </span>
            <span class="interval">:</span>
            <span class="bgNum">
              <span>{{countDownStr.charAt(3)}}</span>
              <span>{{countDownStr.charAt(4)}}</span>
            </span>
            <span class="interval">:</span>
            <span class="bgNum">
              <span>{{countDownStr.charAt(6)}}</span>
              <span>{{countDownStr.charAt(7)}}</span>
            </span>
          </div>
        </div>
        <div class="stopSale" v-if="isStopSale">
          <img :src="stopSaleImg" alt="">
        </div>
      </div>
      <div class="lotteryHeadRight relative">
        <div class="lotHeadRight">
          <div class="lotHeadMun" v-if="resultsNum === 0">
            <div class="lotContTitle lotHeadTitle">
              <p>{{lotteryHeaderData.name}} 第 <span>{{lotteryHeaderData.number}}</span> 期</p>
            </div>
            <div class="lotContList"
                 :class="{happyBJ8: _Format.formatCode($route.query.code).happy8 || _Format.formatCode($route.query.code).pk10}"
                 v-if="lotteryHeaderData.data">
              <!--<p v-for="d in lot.data">{{d}}</p>-->
              <!--PC蛋蛋 加拿大28 台湾28--->
              <p v-for="(award,i) in lotteryHeaderData.data" class="pcVeryCls"
                 v-if="_Format.formatCode($route.query.code).add && i < 3">{{award}}</p>
              <p v-if="_Format.formatCode($route.query.code).add" class="pcVeryCls"
                 :class="{'red': _Format.lotColor(_Util.sumNum(lotteryHeaderData.data), $route.query.code) === 'red', 'green': _Format.lotColor(_Util.sumNum(lotteryHeaderData.data), $route.query.code) === 'green', 'blue': _Format.lotColor(_Util.sumNum(lotteryHeaderData.data), $route.query.code) === 'blue', 'gray': _Format.lotColor(_Util.sumNum(lotteryHeaderData.data), $route.query.code) === 'gray'}">
                {{_Util.sumNum(lotteryHeaderData.data)}}</p>
              <!--广东11选五 重庆时时彩-->
              <p v-for="(award,i) in lotteryHeaderData.data" v-if="_Format.formatCode($route.query.code).isNo">
                {{award}}</p>
              <!--北京pk10-->
              <p v-for="(award,i) in lotteryHeaderData.data" v-if="_Format.formatCode($route.query.code).pk10"
                 class="bjPkTen">{{award}}</p>
              <!--北京快乐8-->
              <p v-for="(award,i) in lotteryHeaderData.data" v-if="_Format.formatCode($route.query.code).happy8"
                 class="happyBJ">{{award}}</p>
              <!--江苏快三-->
              <p v-for="(award,i) in lotteryHeaderData.data" class="fastThreeCls"
                 v-if="_Format.formatCode($route.query.code).shares">
                <img :src="_Format.fastImg(award, $route.query.code)" alt="">
              </p>
              <!--重庆时时彩-->
              <section v-if="_Format.formatCode($route.query.code).zodiac" class="lotteryCQ">
                <p v-for="(award,i) in lotteryHeaderData.data"
                   :class="{'red': _Format.lotColor(award, $route.query.code) === 'red', 'green': _Format.lotColor(award, $route.query.code) === 'green', 'blue': _Format.lotColor(award, $route.query.code) === 'blue'}">
                  <span>{{award}}</span>
                  <span class="theZod" v-if="lotteryHeaderData.animals">{{lotteryHeaderData.animals[i]}}</span>
                </p>
              </section>
            </div>
          </div>
          <div class="lotHeadMun" v-if="resultsNum === 1">
            <section class="displayFlex" :class="{'datePayFle8': _Format.formatCode($route.query.code).happy8}"
                     v-for="lot in theLotteryResultsData">
              <p :class="{'datePay8': _Format.formatCode($route.query.code).happy8}">第 <span
                  class="date">{{changeNumber(lot.number)}}</span> 期开奖号码：</p>
              <p class="disNum"
                 :class="{happyBJ8: _Format.formatCode($route.query.code).happy8 || _Format.formatCode($route.query.code).pk10}"
                 v-if="_Format.formatCode($route.query.code).isNo || _Format.formatCode($route.query.code).happy8">
                <span v-for="d in lot.data">{{d}}</span>
              </p>
              <!--pc蛋蛋 加拿大28-->
              <p class="disNum disNumPcVery" v-if="_Format.formatCode($route.query.code).add">
                <span v-for="(d,j) in lot.data"
                      :class="{'red': _Format.lotColor(d, $route.query.code) === 'red' && j >= 3, 'green': _Format.lotColor(d, $route.query.code) === 'green' && j >= 3, 'blue': _Format.lotColor(d, $route.query.code) === 'blue' && j >= 3, 'gray': _Format.lotColor(d, $route.query.code) === 'gray' && j >= 3}">{{d}}</span>
              </p>
              <!--北京pk10-->
              <p class="disNum lotBJpk10" v-if="_Format.formatCode($route.query.code).pk10">
                <span v-for="d in lot.data">{{d}}</span>
              </p>
              <!--江苏快三-->
              <p class="disNum fastThree" v-if="_Format.formatCode($route.query.code).shares">
                <span v-for="d in lot.data"><img :src="_Format.fastImg(d, $route.query.code)" alt=""></span>
              </p>
              <!--快乐六合彩-->
              <p class="disNum happyLH" v-if="_Format.formatCode($route.query.code).zodiac">
                <span v-for="d in lot.data"
                      :class="{'red': _Format.lotColor(d, $route.query.code) === 'red', 'green': _Format.lotColor(d, $route.query.code) === 'green', 'blue': _Format.lotColor(d, $route.query.code) === 'blue'}">{{d}}</span>
              </p>
            </section>
          </div>
          <div class="lotHeadBtn">
            <p :class="{'active': resultsNum === 0}" @click="lotteryResults(0)">近一期</p>
            <p :class="{'active': resultsNum === 1}" @click="lotteryResults(1)">近五期</p>
          </div>
        </div>
        <div class="ruleAndChartBox">
          <router-link class="relative" :to="{name:'colorRules',query:{code:$route.query.code}}" tag="p"><i
              class="ruleIcon"></i>玩法规则
          </router-link>
          <router-link class="relative" :to="{name:'theResults',query:{code:$route.query.code,name:lotteryName}}"
                       tag="p"><i class="historyIcon"></i>开奖历史
          </router-link>
        </div>
      </div>
    </div>
    <!--封盘音效-->
    <audio :src="indexPlate" class="indexAudio"></audio>
    <!--最新开奖结果音效-->
    <audio :src="indexOpenLottery" class="indexlotteryWav"></audio>
  </div>
</template>

<script>
  import './lotteryHead.scss';
  import {mapState} from 'vuex';
  
  export default {
    data() {
      return {
        lotteryPlayTabData: ['官方玩法', '信用玩法'],
        theLotteryResultsData: [],
        awardHeaderData: {
          data: [],
          listData: []
        }, //开奖数据
        stopSaleImg: require("../../../../assets/images/theColor/header/stopSacle.png"),
        isStopSale: false, //是否停售
        lotteryId: 0, //彩种id
        lotteryName: '', //彩种id
        resultsNum: 0,
        lotteryHeaderData: '', //数据
        tabPlayTrue: 0, //官方信用切换
        countDownStr: '00:00:00', //倒计时值
        countDownSecond: '',//倒计时
        stopBetCountDownSecond: '',//封盘倒计时
        stopBet: false,
        interValObj: '',//是否关闭倒计时
        holdBack: false, //阻止两次请求
        indexPlate: require('../../../../assets/audio/plate.wav'), //封盘音乐
        indexOpenLottery: require('../../../../assets/audio/lottery.wav'), //开奖音乐
        lotTimeNumber: 0,
        localWave: '', //获取本地色波
        setTimer: null,
        numberLot: '',//当前期号
        nextnumberLot: '',//下一期期号
      }
    },
    computed: {
      ...mapState({
        lot: state => state.mutations.recordColorData,
      })
    },
    created() {
      this.initData();
//      this.activation();
    },
    activated() {
      this.clearNumber();
      if (!this.holdBack) return;
      this.initData();
    },
    mounted() {
    },
    deactivated() {
      let that = this;
      window.clearInterval(that.interValObj);
      window.clearInterval(that.setTimer);
      that.isStopSale = false;
    },
    methods: {
      //监听浏览器当前页面是否被激活的事件
      activation() {
        let that = this;
        let reLoadLeftTime = false;
        //监听浏览器当前页面是否被激活的事件
        let hiddenProperty = 'hidden' in document ? 'hidden' : 'webkitHidden' in document ? 'webkitHidden' : 'mozHidden' in document ? 'mozHidden' : null;
        let visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
        let onVisibilityChange = function () {
          if (!document[hiddenProperty]) {
            reLoadLeftTime = true;
            window.cancelAnimFrame = (function () {
              return window.cancelAnimationFrame ||
                window.webkitCancelAnimationFrame ||
                window.mozCancelAnimationFrame ||
                function (id) {
                  clearTimeout(id);
                };
            })();
            that.initData();
          }
        }
        document.addEventListener(visibilityChangeEvent, onVisibilityChange);
        
        that.$router.beforeEach((route, redirect, next) => {
          document.removeEventListener(visibilityChangeEvent, onVisibilityChange);
          next();
        });
      },
      //请求彩种信息接口
      initData() {
        let that = this,
          lotteryId = that.$route.query.code,
          lotteryTrue = that.$route.query.lotteryTrue;
        if (!lotteryId) return;
        if (lotteryTrue) {
          that._Util.post(that, that._Api.POST_CREDIT_LOTTERY_DATA, {lotteryCode: lotteryId}, (data) => {
            that.holdBack = true;
            that.isStopSale = data.status == '1' ? false : true;
            //获取数据
            that.lotteryHeaderData = JSON.parse(JSON.stringify(data));
            //获取前五期数据
            if (data.dataLit) {
              that.theLotteryResultsData = that.changeFiveData(data.dataLit);
            }
            //彩种id
            that.lotteryId = data.code;
            that.lotteryName = data.name;
            if (that._Format.determineColor(that.lotteryId).letter) {
              that.tabPlayTrue = 1
            } else {
              that.tabPlayTrue = 0;
            }
            //倒计时数据
            that.countDownSecond = data.countDown || -1;
            that.stopBetCountDownSecond = data.stopCountDown;
            that.startCountDown();
            /*处理官方数据*/
            if (that._Format.determineColor(that.lotteryId).officer) {
              let localDataLog = that.$parent.localData;
              if (!localDataLog) return;
              data.groupList.forEach((v, i) => {
                v.playList.forEach((p, j) => {
                  if (p.dataList) {
                    p.dataList.forEach((d, y) => {
                      //处理本地数据
                      localDataLog.groupList.forEach((BV, w) => {
                        if (v.code === BV.code) {
                          BV.playList.forEach((BP, e) => {
                            if (p.code === BP.code) {
                              BP.dataList.forEach((BD, r) => {
                                if (d.id === BD.id) {
                                  d.localData = BD.localData;
                                }
                              })
                            }
                          })
                        }
                      })
                    })
                  }
                })
              })
            }
            if (!that.isStopSale) {
              that.numberLot = data.number;
              that.nextnumberLot = data.nowNumber;
              that.upDateLastData();
            }
            let lotteryData = {
              id: parseInt(that.$route.query.code),
              data: data
            };
            that._Util.setItem('dataSetItem', data.groupList);
            that.$store.commit('RECORD_COLOR_DATA', lotteryData);
            that.$store.commit('INIT_LOTTERY_DATA', lotteryData.data);
          });
        }
      },
      //近五期数据处理
      changeFiveData(data) {
        let pcNuber = 0;
        data.forEach((m, n) => {
          if (this._Format.formatCode(this.$route.query.code).add) {
            pcNuber = this._Util.sumNum(m.data);
            m.data.push(pcNuber);
          }
        });
        return data;
      },
      //清除期号
      clearNumber() {
        this.nextnumberLot = '';
        this.numberLot = '';
      },
      //期号处理
      changeNumber(num) {
        let code = this.$route.query.code;
        if (code == '1002'||code=='026') {
          return num.slice(4);
        }else{
          return num;
        }
      },
      // 更新新的一期开奖结果
      upDateLastData() {
        let that = this;
        that.setTimer = setInterval(() => {
          if (parseInt(that.nextnumberLot) - parseInt(that.numberLot) === 1 || !that.$route.query.code) {
            clearInterval(that.setTimer);
          } else {
            let submitData = {
              lotteryCode: that.$route.query.code
            };
            if (!that.isStopSale) {
              that._Util.post(that, that._Api.POST_LOTTERY_DATA_LAST, submitData, (data) => {
                // 更新期号
//                that.lotPerNumber = data.openDataList[0].number;
                // 更新开奖号码
                if(data.openDataList.length>0){
                  that.lotteryHeaderData.animals = data.openDataList[0].animals||[];
                  that.lotteryHeaderData.code = data.openDataList[0].code;
                  that.lotteryHeaderData.color = data.openDataList[0].color;
                  that.lotteryHeaderData.data = data.openDataList[0].data;
                  that.lotteryHeaderData.number = data.openDataList[0].number;
                  that.numberLot = data.openDataList[0].number;
                }
                that.lotteryHeaderData.nowNumber = data.nextNumber;
                that.nextnumberLot = data.nextNumber;
                // 获取近五期开奖数据
                that.theLotteryResultsData = that.changeFiveData(data.openDataList||[]);
              }, (data) => {
                clearInterval(that.setTimer);
              }, '', true);
            } else {
              clearInterval(that.setTimer);
            }
          }
        }, 3000);
      },
      //倒计时方法
      startCountDown() {
        let that = this;
        that.$store.state.mutations.bottomPourData = false;
        that.stopBet = false;
        window.clearInterval(that.interValObj);
        if (that.countDownSecond > 0 && !that.isStopSale) {
          that.interValObj = window.setInterval(
            function () {
              if (that.$route.query.lotteryTrue) {
                that.countDown();
              }
            }.bind(this), 1000);
        }
      },
      countDown() {
        let that = this;
        //倒计时
        if (that.countDownSecond > 0) {
          that.lotTimeNumber = 0;
          that.countDownSecond = that.countDownSecond - 1;
          if (that.stopBetCountDownSecond > 0) {
            that.stopBetCountDownSecond -= 1;
          } else {
            if (that.stopBetCountDownSecond === 0) {
              that._Util.showAlert('已封盘');
              that.plateOpen();
              that.$store.state.mutations.bottomPourData = true;
            }
            that.stopBetCountDownSecond -= 1;
            that.stopBet = true;
          }
          that.countDownStr = that._Util.formatTime(that.stopBetCountDownSecond, that.countDownSecond, that.stopBet);
        } else if (that.countDownSecond === 0) {
          //回调方法
          if (that.lotTimeNumber === 0) {
            that._Util.showAlert('新的一期已经开始');
          } else if (that.lotTimeNumber === 3) {
            that._Util.showAlert('刷新页面重试');
            window.location.reload();
            return;
          }
          that.$parent.setABetTrue = false;
          that.stopBet = false;
          // that.headerInitData();
          that.initData();
          that.lotTimeNumber += 1;
        }
      },
      //封盘音效
      plateOpen() {
        let indexAudio = document.getElementsByClassName('indexAudio')[0];
        indexAudio.play();
      },
      //信用官方玩法切换
      creditTab(index) {
        let that = this;
        let code = that.$route.query.code;
        if (that.tabPlayTrue != index) {
          if (that._Util.checkLotteryCode(code) == '-1') {
            that._Util.showAlert("暂时还未开通该玩法哦");
          } else {
            // console.log('that._Format.determineColor(code).letter', that._Format.determineColor(code).letter)
            code = that._Util.checkLotteryCode(code);
            if (that._Format.determineColor(code).letter) {
              that.$router.push({name: 'credit', query: {code: code, index: parseInt(code), lotteryTrue: true}});
            } else {
              that.$router.push({name: 'official', query: {code: code, index: parseInt(code), lotteryTrue: true}});
            }
          }
        }
      },
      //初始化数据
      headerInitData() {
        let that = this;
        if (that._Format.determineColor(that.$route.query.code).letter) {
          that.$parent.$refs.creditThe.init();
        }
      },
      lotteryResults(index) {
        this.resultsNum = index;
      }
    },
    watch: {
      '$parent.localData'() {
        let t = this.$route.query.lotteryTrue ? this.$route.query.lotteryTrue : '';
        if (!t) return;
        this.initData();
      },
      '$route.query.code'() {
        let that = this;
        if (this.$route.name === 'credit' || this.$route.name === 'official') {
          that.initData();
        }
      },
      '$parent.$refs.creditThe.thatBDVal'() {
        // this.initLocal();
      }
    }
  }
</script>
